package com.jlcloud.core.oauth2.service.impl;

import lombok.AllArgsConstructor;
import com.jlcloud.core.oauth2.constant.OAuth2UserConstant;
import com.jlcloud.core.oauth2.provider.OAuth2Request;
import com.jlcloud.core.oauth2.service.OAuth2User;
import com.jlcloud.core.oauth2.service.OAuth2UserService;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Optional;

/**
 * 获取用户详情
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
@AllArgsConstructor
public class OAuth2UserDetailService implements OAuth2UserService {

	private final JdbcTemplate jdbcTemplate;

	@Override
	public OAuth2User loadByUserId(String userId, OAuth2Request request) {
		try {
			return jdbcTemplate.queryForObject(OAuth2UserConstant.DEFAULT_USERID_SELECT_STATEMENT, new BeanPropertyRowMapper<>(OAuth2UserDetail.class), userId);
		} catch (Exception ex) {
			return null;
		}
	}

	@Override
	public OAuth2User loadByUsername(String username, OAuth2Request request) {
		try {
			return jdbcTemplate.queryForObject(OAuth2UserConstant.DEFAULT_USERNAME_SELECT_STATEMENT, new BeanPropertyRowMapper<>(OAuth2UserDetail.class), username);
		} catch (Exception ex) {
			return null;
		}
	}

	@Override
	public OAuth2User loadByPhone(String phone, OAuth2Request request) {
		try {
			return jdbcTemplate.queryForObject(OAuth2UserConstant.DEFAULT_PHONE_SELECT_STATEMENT, new BeanPropertyRowMapper<>(OAuth2UserDetail.class), phone);
		} catch (Exception ex) {
			return null;
		}
	}

	@Override
	public boolean validateUser(OAuth2User user) {
		return Optional.ofNullable(user)
			.filter(u -> u.getUserId() != null && !u.getUserId().isEmpty()) // 检查userId不为空
			.filter(u -> u.getAuthorities() != null && !u.getAuthorities().isEmpty()) // 检查authorities不为空
			.isPresent(); // 如果上述条件都满足，则返回true，否则返回false
	}
}
